<?php
/**
 * Created by PhpStorm.
 * User: ZhengYaFeng
 * Date: 2016/10/17
 * Time: 15:27
 */
namespace App\Http\Controllers\Admin\AdminUser;

use App\Helper\Helpers;
use App\Http\Controllers\AdminController;
use App\Http\Controllers\Controller;
use App\Http\Requests\StoreAdminiUser;
use Illuminate\Support\Facades\DB;
class AdminiUserController extends AdminController
{
    /**
     * 用户管理列表页...
     * @author  <ZhengYaFeng>
     * @data    <Y-m-d H:i:s>
     * @access  <public>
     * @return  <view用户管理列表页>
     * @des     <描述:>
     * @return mixed
     */
    public function index()
    {
        $data = array();
        $data['list'] = DB::table('adminuser')
                            ->select('adminuser.*','admini_group.name')
                            ->leftJoin('admini_group','adminuser.group_master_id','=','admini_group.id')
                            ->where('status',1)
                            ->paginate(10);
        return \Helpers::showViewCURD('Admin.AdminUser.index',3,'',$data);
    }

    /**
     * 用户管理新增页...
     * @author  <ZhengYaFeng>
     * @data    <Y-m-d H:i:s>
     * @access  <public>
     * @return  <view>
     * @des     <描述:>
     * @return mixed
     */
    public function create()
    {
        $data = array();
        $list = $this->get_group_data();
        $data['get_group_data'] = \Helpers::getTreeSelect($list,'',0,1);
        $data['get_servant_id'] = '';
        if(!empty($list))
        {
            foreach($list as $key => $value){
                $data['get_servant_id'] .= '<option value="'.$value->id.'">'.$value->name.'</option>';
            }
        }
        return \Helpers::showViewCURD('Admin.AdminUser.create',1,'新增',$data);
    }

    /**
     * 获取组信息...
     * @author  <ZhengYaFeng>
     * @data    <Y-m-d H:i:s>
     * @access  <public>
     * @return  <view>
     * @des     <描述:获取组信息>
     * @param string $id
     * @return mixed
     */
    private function get_group_data($id = '')
    {
        if(!empty($id)){
            $list = DB::select('
                        select id,pid,path,name,concat(path,",",id) as bpath 
                        from wj_admini_group 
                        where is_del = ? 
                        and id != ?
                        order by bpath 
                    ',[1,$id]);
        }else{
            $list = DB::select('
                        select id,pid,path,name,concat(path,",",id) as bpath 
                        from wj_admini_group 
                        where is_del = ? 
                        order by bpath 
                    ',[1]);
        }
        return $list;
    }

    /**
     * 新增操作...
     * @author  <ZhengYaFeng>
     * @data    <Y-m-d H:i:s>
     * @access  <public>
     * @return  <view>
     * @des     <描述:新增操作>
     * @param StoreAdminiUser $request
     * @return $this
     */
    public function store(StoreAdminiUser $request)
    {
        //验证post提交
        if($request->isMethod('post')) {
            $post = $request->all();
            if(empty($post['password'])) return redirect()->back()->withErrors('密码必填!');
            $inserArr = $this->addOrEditFormatD($post);
            //入库
            $res = DB::table('adminuser')->insertGetId($inserArr);
            $errors = $res ? '新增成功!' : '新增失败!';
            $isSuccess = $res ? 'success' : 'error';
            \Helpers::insertUserActionLog('rbacUser','add',$res,$isSuccess,$inserArr);
            return redirect()->back()->withErrors($errors);
        }else{
            abort(404);
        }
    }

    /**
     * 格式化新增修改表单提交数据...
     * @author  <ZhengYaFeng>
     * @data    <Y-m-d H:i:s>
     * @access  <public>
     * @return  <view>
     * @des     <描述:格式化新增修改表单提交数据>
     * @param $post
     * @param string $addOrEdit
     * @return $this|array
     */
    public function addOrEditFormatD($post,$addOrEdit = 'add')
    {
        $arr = array();
        //新增或修改公共入库数据
        $group_master_id = explode('_', $post['group_master_id']);
        $arr['group_master_id'] = $group_master_id[1];
        $servant_str = '';
        if(!empty($post['group_servant_id']))
        {
            foreach($post['group_servant_id'] as $k => $v)
            {
                $servant_str.= $v.',';
            }
            $arr['group_servant_id'] = rtrim($servant_str,',');
        }else{
            $arr['group_servant_id'] = '';
        }
        //新增或修改不同入库数据
        if($addOrEdit == 'add')
        {
            $arr['username'] = $post['username'];
            $arr['password'] = password_hash($post['password'], PASSWORD_DEFAULT);
            $newUserNameExist = DB::table('adminuser')->where('username',$arr['username'])->count();
            if($newUserNameExist>= 1) return redirect()->back()->withErrors('添加失败，后台存在同名用户!');
            $arr['create_time'] = time();
        }else{
            $arr['password'] = empty($post['password']) ? $post['oldpassword'] : password_hash($post['password'], PASSWORD_DEFAULT);
            $arr['update_time'] = time();
        }
        return $arr;
    }

    /**
     * 修改页面...
     * @author  <ZhengYaFeng>
     * @data    <Y-m-d H:i:s>
     * @access  <public>
     * @return  <view>
     * @des     <描述:修改页面>
     * @param $id
     * @return mixed
     */
    public function edit($id)
    {
        //验证数据
        if(empty($id) || (!empty($id) && $id == 1)) abort(404);
        $data = array();
        $data['editList'] = DB::table('adminuser')->where('id',$id)->first();
        $list = $this->get_group_data();
        $list_s = $this->get_group_data($data['editList']->group_master_id);
        $data['get_group_data'] = \Helpers::getTreeSelect($list,$data['editList']->group_master_id,1,1);
        $data['get_servant_id'] = '';
        if(!empty($list_s))
        {
            $explode = empty($data['editList']->group_servant_id)? '' : explode(',',$data['editList']->group_servant_id);
            foreach($list_s as $key => $value){
                if(!empty($data['editList']->group_servant_id) && in_array($value->id,$explode))
                {
                    $data['get_servant_id'] .= '<option value="'.$value->id.'" selected="selected">'.$value->name.'</option>';
                }else{
                    $data['get_servant_id'] .= '<option value="'.$value->id.'">'.$value->name.'</option>';
                }
            }
        }
        return \Helpers::showViewCURD('Admin.AdminUser.create',2,'修改',$data);
    }

    /**
     * 修改操作...
     * @author  <ZhengYaFeng>
     * @data    <Y-m-d H:i:s>
     * @access  <public>
     * @return  <view>
     * @des     <描述:修改操作>
     * @param $id
     * @param StoreAdminiUser $request
     * @return $this
     */
    public function update($id,StoreAdminiUser $request)
    {
        if(empty($id) || (!empty($id) && $id == 1)) abort(404);
        //验证post提交
        $post = $request->all();
        $editArr = $this->addOrEditFormatD($post,'up');
        $res = DB::table('adminuser')
            ->where('id',intval($id))
            ->update($editArr);
        //根据入库结果返回状态
        $errors = $res ? '修改成功!' : '修改失败!';
        $isSuccess = $res ? 'success' : 'error';
        \Helpers::insertUserActionLog('rbacUser','up',$id,$isSuccess,$editArr);
        return redirect()->back()->withErrors($errors);
    }

    /**
     * 删除操作...
     * @author  <ZhengYaFeng>
     * @data    <Y-m-d H:i:s>
     * @access  <public>
     * @return  <view>
     * @des     <描述:删除操作>
     * @param $id
     * @return string
     */
    public function del($id)
    {
        //验证传参,ac 1.逻辑删除 2.物理删除 3.还原
        if(empty($id) || empty($_POST['ac']) || (!empty($id) && $id == 1)) abort(404);
        $status = $_POST['ac'];
        //status:1.逻辑删除数据,2.物理删除数据
        if($status == 1) $res = DB::table('adminuser')->where('id',intval($id))->update(array('status'=>2));
        if($status == 2) $res = DB::table('adminuser')->where('id',intval($id))->delete();
        $preMsg = '删除';
        $errorCode = $res ? 1 : -1;
        $msg = $res ? $preMsg.'成功!' : $preMsg.'失败!';
        $isSuccess = $res ? 'success' : 'error';
        \Helpers::insertUserActionLog('rbacUser','del',$id,$isSuccess,$_POST);
        return json_encode(array('error'=>$errorCode,'msg'=>$msg));
    }

    /**
     * 数据还原...
     * @author  <ZhengYaFeng>
     * @data    <Y-m-d H:i:s>
     * @access  <public>
     * @return  <view>
     * @des     <描述:数据还原>
     * @param $id
     * @return string
     */
    public function back($id)
    {
        //验证传参,ac 1.逻辑删除 2.物理删除 3.还原
        if(empty($id) || empty($_POST['ac']) || (!empty($id) && $id == 1)) abort(404);
        //还原逻辑删除数据
        $res = DB::table('adminuser')->where('id',intval($id))->update(array('status'=>1));
        $preMsg = '还原';
        $errorCode = $res ? 1 : -1;
        $msg = $res ? $preMsg.'成功!' : $preMsg.'失败!';
        $isSuccess = $res ? 'success' : 'error';
        \Helpers::insertUserActionLog('rbacUser','back',$id,$isSuccess,$_POST);
        return json_encode(array('error'=>$errorCode,'msg'=>$msg));
    }

    /**
     * 回收站...
     * @author  <ZhengYaFeng>
     * @data    <Y-m-d H:i:s>
     * @access  <public>
     * @return  <view>
     * @des     <描述:回收站>
     * @return mixed
     */
    public function rb()
    {
        $data = array();
        $data['list'] = DB::table('adminuser')
            ->select('adminuser.*','admini_group.name')
            ->leftJoin('admini_group','adminuser.group_master_id','=','admini_group.id')
            ->where('status',2)
            ->paginate(10);
        return \Helpers::showViewCURD('Admin.AdminUser.index',4,'',$data);
    }
}